package com.pfizer.pfizerExpertForPad;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.pfizer.Entity.DoctorInfo;
import com.pfizer.Entity.HospitalInfo;
import com.pfizer.Entity.UserInfo;
import com.pfizer.Public.PublicFunc;
import com.pfizer.XmlContentHandler.SaxReadXml;

public class PunchCardDialog extends Activity implements OnFocusChangeListener,OnClickListener,OnKeyListener {

	Spinner hospitalSel = null;
	Spinner doctorSel = null;
	Spinner activityItemSel = null;
	ImageButton sendCardBt = null;
	ImageButton cancleCardBt = null;
	EditText etHosp = null;
	EditText etDoctor = null;
	EditText etActivityInput = null;
	Context mContext = PunchCardDialog.this;
	pfizerApplication pApplication = null;
	//InputStream inputStream = null;
	List<HospitalInfo> hospitalInfosList = new ArrayList<HospitalInfo>();
	List<DoctorInfo> doctorInfosList = new ArrayList<DoctorInfo>();
	String hospCode = "";
	String doctorCode = "";
	// 需要上傳的值
	UserInfo loginUser;
	String activityStr;
	int HospCurrPosition = 0;
	int DrCurrPosition = 0;
	Thread thdCreateRecordComplete = null;
	Thread thdGetHospList = null;
	Thread thdGetDoctorList = null;
	Handler handler = null;
	ProgressDialog progressDialog1;
	ProgressDialog progressDialog2;
	ProgressDialog progressDialog3;

	String PunchCardRecordCompleteUrlStrTest = "";
	String PunchCardRecordCompleteUrlStr = "";
	String PunchCardResult = "";
	private String PCR_IDStr = "";
	private String HospitalUrlFormat = "%s/PENS_CRC/Query.aspx?Switch=User_Hospital&UserID=%s&Obj_From=%s&Obj_ID=%s&ProveCode=%s";
	private String DoctorUrlFormat = "%s/PENS_CRC/Query.aspx?Switch=Hospital_DrList&UserID=%s&HospCode=%s&Obj_From=%s&Obj_ID=%s&ProveCode=%s";
	private String PunchCardRecordCompleteFormatStr = "%s/PENS_Api/Query.aspx?ProveCode=%s&Obj_ID=%s&Obj_From=%s&Which=PunchCardRecord_Complete&UserID=%s&UserName=%s&PCR_ID=%s&Hospital_ID=%s&Hospital_Name=%s&Dr_ID=%s&Dr_NAME=%s&Activity_Input=%s&OffDuty_Lat=%s&OffDuty_Lng=%s";
	private String[] activityItem = null;
	ArrayAdapter<HospitalInfo> adapter_hospital = null;
	ArrayAdapter<DoctorInfo> adapter_doctor = null;

	InputMethodManager m = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		m = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.punchcarddialog);
		InitApp initApp = new InitApp(mContext);
		initApp.SetApp(0);
		pApplication = (pfizerApplication) getApplicationContext();
		Intent intent = getIntent();
		PCR_IDStr = intent.getStringExtra("PCR_ID");
		hospitalSel = (Spinner) findViewById(R.id.hospital_sel);
		hospitalSel.setOnFocusChangeListener(this);
		doctorSel = (Spinner) findViewById(R.id.doctor_sel);
		doctorSel.setOnFocusChangeListener(this);
		activityItemSel = (Spinner) findViewById(R.id.doctor_other);
		etHosp = (EditText) findViewById(R.id.hospital_input);
		etHosp.setOnKeyListener(this);
		etDoctor = (EditText) findViewById(R.id.doctor_input);
		etDoctor.setOnKeyListener(this);
		etActivityInput = (EditText) findViewById(R.id.input_activity_reason);
		etActivityInput.setOnKeyListener(this);
		activityStr = etActivityInput.getText().toString();
		activityItem = getResources().getStringArray(R.array.activityItem);
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);

				switch (msg.what) {
				case 9:
					if (progressDialog3 != null) {
						progressDialog3.dismiss();
					}
					adapter_doctor = new ArrayAdapter<DoctorInfo>(mContext,
							android.R.layout.simple_spinner_item,
							doctorInfosList);
					adapter_doctor
							.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					doctorSel.setPrompt("請選擇醫生");
					doctorSel.setAdapter(adapter_doctor);
					adapter_doctor.notifyDataSetChanged();
					break;
				case 6:
					if (progressDialog2 != null) {
						progressDialog2.dismiss();
					}
					adapter_hospital = new ArrayAdapter<HospitalInfo>(mContext,
							android.R.layout.simple_spinner_item,
							hospitalInfosList);
					adapter_hospital
							.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					hospitalSel.setPrompt("請選擇醫院");
					hospitalSel.setAdapter(adapter_hospital);
					adapter_hospital.notifyDataSetChanged();
					break;
				case 1:
					if (progressDialog1 != null) {
						progressDialog1.dismiss();
					}
					Toast.makeText(mContext, "打卡已經送出！", Toast.LENGTH_SHORT)
							.show();
					Intent intent = new Intent(PunchCardDialog.this,
							PunchCardActivity.class);
					setResult(RESULT_OK, intent);
					finish();
					break;
				case -1:
					if (progressDialog1 != null) {
						progressDialog1.dismiss();
					}
					Toast.makeText(mContext, "打卡出错！", Toast.LENGTH_SHORT)
							.show();
					break;
				case -2:
					if (progressDialog2 != null) {
						progressDialog2.dismiss();
					}
					Toast.makeText(mContext, "取得醫院信息失败!", 1).show();
					break;
				case -3:
					if (progressDialog2 != null) {
						progressDialog2.dismiss();
					}
					Toast.makeText(mContext, "取得醫院信息失败!", 1).show();
					break;
				case -4:
					if (progressDialog3 != null) {
						progressDialog3.dismiss();
					}
					Toast.makeText(mContext, "取得醫生信息失败!", 1).show();
				case -5:
					if (progressDialog3 != null) {
						progressDialog3.dismiss();
					}
					Toast.makeText(mContext, "取得醫生信息失败!", 1).show();
				default:
					break;
				}
			}
		};

		getHospitalInfo();
		hospitalSel.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				HospCurrPosition = position;
				hospCode = hospitalInfosList.get(position).getHospCode();// 作为参数去请求医生数据列表
				String hospName = hospitalInfosList.get(position).getHospName();

				if (position == 0) {
					etHosp.setEnabled(true);
					etHosp.setText("");
				} else {
					etHosp.setEnabled(false);
					etHosp.setText(hospName);
				}
				// 執行線程獲取醫生信息
				getDoctorInfo(hospCode);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		});

		doctorSel.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				DrCurrPosition = position;
				doctorCode = doctorInfosList.get(position).getDoctorCode();
				String doctorName = doctorInfosList.get(position)
						.getDoctorName();

				if (position == 0) {
					etDoctor.setEnabled(true);
					etDoctor.setText("");
				} else {
					etDoctor.setEnabled(false);
					etDoctor.setText(doctorName);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		ArrayAdapter<CharSequence> activityAdapter = ArrayAdapter
				.createFromResource(mContext, R.array.activityItem,
						android.R.layout.simple_spinner_item);
		activityAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		activityItemSel.setAdapter(activityAdapter);
		activityItemSel.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				if (position == 0) {
					//etActivityInput.setVisibility(View.GONE);
					activityStr = "";
					etActivityInput.setText(activityStr);
				} else {
					activityStr = activityItem[position];
					etActivityInput.setText(activityStr);
					//etActivityInput.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
		sendCardBt = (ImageButton) findViewById(R.id.sendcardBt);
		cancleCardBt = (ImageButton) findViewById(R.id.canclecardBt);
		sendCardBt.setOnClickListener(this);
		cancleCardBt.setOnClickListener(this);

	}

	private void getHospitalInfo() {
		progressDialog2 = ProgressDialog.show(mContext, null,
				"正在獲取醫院信息，請稍後...", true, false);
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				//			
				//inputStream = null;
				// 这里需要获取到的UserName作为参数构成以下urlstr
				String urlStr = String.format(HospitalUrlFormat, pApplication
						.getWebUrl(), pApplication.getUserID(), pApplication
						.getObjFrom(), pApplication.getObjID(), pApplication
						.getUserLoginProveCode());
				Message msg = new Message();
				HospitalInfo hInfo = new HospitalInfo();
				hInfo.setHospCode("9999999999");
				hInfo.setHospName("自行輸入");
				hospitalInfosList.add(hInfo);
				InputStream inStream=null;
				try {
					URL url = new URL(urlStr);
					//inputStream = url.openStream();
					HttpURLConnection urlCon=(HttpURLConnection)url.openConnection();
					urlCon.setConnectTimeout(30*1000); 
					urlCon.setReadTimeout(30*1000); 
					int responseCode=urlCon.getResponseCode();
					if(responseCode==HttpURLConnection.HTTP_OK)
					{
						inStream=urlCon.getInputStream();
					}
				} catch (IOException ex) {
					msg.what = -2;
					handler.sendMessage(msg);
					return;
				}
				try {
					hospitalInfosList = SaxReadXml
							.readHospitalInfo(inStream);
					msg.what = 6;
					handler.sendMessage(msg);
					hospitalInfosList.add(0, hInfo);
				} catch (Exception ex) {
					msg.what = -3;
					handler.sendMessage(msg);
					return;
				}
			}
		}).start();
	}

	private void getDoctorInfo(final String hospCode) {

		doctorInfosList.clear();
		if (hospCode.equals("9999999999")) {
			DoctorInfo dInfo = new DoctorInfo();
			dInfo.setDoctorCode("9999999999");
			dInfo.setDoctorName("自行輸入");
			doctorInfosList.add(dInfo);
			Message msg = new Message();
			msg.what = 9;
			handler.sendMessage(msg);
			return;
		}
		progressDialog3 = ProgressDialog.show(mContext, null,
				"正在獲取醫生信息，請稍後...", true, false);
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				//	
				InputStream inStream = null;
				// 这里需要获取到的UserName作为参数构成以下urlstr
				String urlStr = String.format(DoctorUrlFormat, pApplication
						.getWebUrl(), pApplication.getUserID(), hospCode,
						pApplication.getObjFrom(), pApplication.getObjID(),
						pApplication.getUserLoginProveCode());
				// urlStr = "http://222.196.236.62/xml/Doctor.xml";
				Message msg = new Message();
				DoctorInfo dInfo = new DoctorInfo();
				dInfo.setDoctorCode("9999999999");
				dInfo.setDoctorName("自行輸入");
				doctorInfosList.add(dInfo);
				try {
					URL url = new URL(urlStr);
					//inputStream = url.openStream();
					HttpURLConnection urlCon=(HttpURLConnection)url.openConnection();
					urlCon.setConnectTimeout(30*1000); 
					urlCon.setReadTimeout(30*1000); 
					int responseCode=urlCon.getResponseCode();
					if(responseCode==HttpURLConnection.HTTP_OK)
					{
						inStream=urlCon.getInputStream();
					}
				} catch (IOException ex) {
					msg.what = -4;
					handler.sendMessage(msg);
					return;
				}
				try {
					doctorInfosList = SaxReadXml.readDoctorInfo(inStream);
					msg.what = 9;
					handler.sendMessage(msg);
					doctorInfosList.add(0, dInfo);
				} catch (Exception ex) {
					msg.what = -5;
					handler.sendMessage(msg);
					return;
				}
			}
		}).start();
	}

	private void CompletePunchCard(final String urlStr) {

		progressDialog1 = ProgressDialog.show(mContext, null, "正在打卡，請稍後...",
				true, false);

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Message msg = new Message();
				InputStream inStream = null;
				try {
					URL url = new URL(urlStr);
					inStream = url.openStream();
					if (PublicFunc.inputStream2String(inStream)
							.equalsIgnoreCase("Y")) {
						// 如果獲取到的字符為Y，則已經查看，更新本地數據
						msg.what = 1;
						handler.sendMessage(msg);
					} else {
						msg.what = -1;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					// TODO: handle exception
					msg.what = -1;
					handler.sendMessage(msg);
				}
			}
		}).start();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int Id = v.getId();
		switch (Id) {
		case R.id.sendcardBt:
			String hospName = etHosp.getText().toString().trim();
			String doctorName = etDoctor.getText().toString().trim();
			if (hospName.length() == 0) {
				Toast.makeText(mContext, "請輸入醫院名稱！", Toast.LENGTH_SHORT).show();
				return;
			}
			if (doctorName.length() == 0) {
				Toast.makeText(mContext, "請輸入醫生姓名！", Toast.LENGTH_SHORT).show();
				return;
			}
			String urlStr = String.format(PunchCardRecordCompleteFormatStr,
					pApplication.getWebUrl(), pApplication.getMainProveCode(),
					pApplication.getObjID(), pApplication.getObjFrom(),
					pApplication.getUserID(), pApplication.getUserName(),
					PCR_IDStr, hospCode, hospName, doctorCode, doctorName,
					activityStr, String.valueOf(pApplication.getDuty_Lat()),
					String.valueOf(pApplication.getDuty_Lng()));
			CompletePunchCard(urlStr);
			break;
		case R.id.canclecardBt:
			((Activity) mContext).finish();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		hospitalSel = null;
		doctorSel = null;
		activityItemSel = null;
		sendCardBt = null;
		cancleCardBt = null;
		etActivityInput = null;
		pApplication = null;
		hospitalInfosList = null;
		doctorInfosList = null;
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// int i=event.getAction();
		if (keyCode == 66 && event.getAction() == KeyEvent.ACTION_UP) {
			int Id = v.getId();
			switch (Id) {
			case R.id.hospital_input:
				etDoctor.requestFocus();
				etDoctor.setSelection(0, etDoctor.getText().toString().length());
				//etUserPwd.setSelection(0, etUserPwd.getText().length());
				break;
			case R.id.doctor_input:
				etActivityInput.requestFocus();
				etActivityInput.setSelection(0, etActivityInput.getText().toString().length());
				break;
			case R.id.input_activity_reason:
				m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
				break;
			default:
				break;
			}
			return true;
		} else if (keyCode == 66 && event.getAction() == KeyEvent.ACTION_DOWN) {
			return true;
		}
		return false;
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		EditText _v=(EditText)v;
        if (!hasFocus) {// 落空核心
            _v.setHint(_v.getTag().toString());
        } else {
            String hint=_v.getHint().toString();
            _v.setTag(hint);
            _v.setHint("");
        }
	}
}
